<?
class AdminController extends BaseController{

    /*
     * Hàm in ra ảnh thumb của 1 bản ghi
     */
    public static function GetImageThumb($thumb){
        global $bg_filepath;
        return '<div class="control-group">
                    <label class="control-label">Ảnh đại diện</label>
                    <div class="controls" style="width: 160px;height:90px;overflow:hidden">
                        <img src="'.$bg_filepath . $thumb.'" alt="Khong co anh"/>
                    </div>
                </div>';
    }

    /*
     * Hàm checksum khi upload giao diện
     */
    public static function ChecksumUploadTemplate($tpl_name, $str){
        global $isAdmin;
        $checksum = self::CreateChecksumTemplate($tpl_name);
        if($isAdmin && $str === $checksum) return true;
        else return false;
    }

    /*
     * Hàm tạo khung chứa kết quả tìm kiếm tin tức liên quan trong admin
     */
    public static function CreateRelateNewsSection(){
        return '<div class="control-group">
                    <div class="controls">
                        <ul id="relate_result"></ul>
                    </div>
                    <div class="controls" id="news_relate_after_search">

                    </div>
                </div>';
    }
    /*
     * Hàm tạo khung chứa kết quả tìm kiếm sản phẩm liên quan trong admin
     */
    public static function CreateRelateProSection(){
        return '<div class="control-group">
                    <div class="controls">
                        <ul id="relate_pro_result"></ul>
                    </div>
                    <div class="controls" id="pro_relate_after_search">

                    </div>
                </div>';
    }


    /*
     * Hàm tìm kiếm tin tức dựa vào từ khóa
     */
    public static function SearchNewsRelate($keyword){
        $str = '';
        $db_se = new db_query('SELECT new_id,new_title FROM news
                                WHERE new_active = 1 AND (new_title LIKE "%'.$keyword.'%" OR new_tags LIKE "%'.$keyword.'%")
                                ORDER BY new_title ASC
                                LIMIT 10 ' );
        $result = $db_se->resultArray();unset($db_se);
        $result = array_unique($result,SORT_REGULAR);
        if($result){
            foreach($result as $lir){
                $str .= '
                    <li>
                        <label class="checkbox">
                            <input type="checkbox" title="'.$lir['new_title'].'" value="'.$lir['new_id'].'" class="new_relate_result" id="search_news_relate_'.$lir['new_id'].'"/>
                            '.$lir['new_title'].'
                        </label>
                    </li>';
            }
            $str .= '<span class="label label-info" style="cursor:pointer" onclick="NewsJS.add_relate()">Thêm vào</span>';
        }
        return $str;
    }

    /*
     * Hàm lấy ra hộp combobox các tin khuyến mại để add vào product
     */
    public static function ComboboxPromotionNews(){
        global $global_category_config;
        $id = $global_category_config['promotionID'];
        $db = new db_query('SELECT new_id,new_title
                            FROM news
                            WHERE new_cat_id = '.$id);
        $list_news = array(''=>'Chọn một hoặc nhiều chương trình khuyến mại');
        while($row = mysql_fetch_assoc($db->result)){
            $list_news[$row['new_id']] = cut_string($row['new_title'],50);
        }
        return $list_news;
    }
    /*
     * Hàm lấy ra danh mục các phụ kiện theo combobox
     */
    public static function ComboboxListComboCategory(){
        $db = new db_query('SELECT cat_id, cat_name
                            FROM categories_multi
                            WHERE cat_type = "combo"');
        $list_cat = array();
        while($row = mysql_fetch_assoc($db->result)){
            $list_cat[$row['cat_id']] = $row['cat_name'];
        }
        return $list_cat;
    }

    /*
     * Hàm tìm kiếm sản phẩm dựa vào từ khóa
     */
    public static function SearchProRelate($keyword){
        $str = '';
        $db_se = new db_query('SELECT pro_id,pro_name
                                FROM products
                                WHERE pro_active = 1
                                    AND (pro_name LIKE "%'.$keyword.'%")
                                ORDER BY pro_name ASC
                                LIMIT 10 ' );
        $result = $db_se->resultArray();unset($db_se);
        $result = array_unique($result,SORT_REGULAR);
        if($result){
            foreach($result as $lir){
                $str .= '
                    <li>
                        <label class="checkbox">
                            <input type="checkbox" title="'.$lir['pro_name'].'" value="'.$lir['pro_id'].'" class="pro_relate_result" id="search_pro_relate_'.$lir['pro_id'].'"/>
                            '.$lir['pro_name'].'
                        </label>
                    </li>';
            }
            $str .= '<span class="label label-info" style="cursor:pointer" onclick="ProductJS.add_relate()">Thêm vào</span>';
        }
        return $str;
    }

    /*
     * Hàm show list dữ liệu liên quan
     */
    public static function ShowRelateData($relate_str, $type = 'news'){
        $str = '';
        switch($type){
            case 'news' :
                if(!$relate_str) return self::CreateRelateNewsSection();
                $db_query = new db_query('SELECT new_id,new_title
                                    FROM news
                                    WHERE new_active = 1 AND new_id IN('.$relate_str.')');
                $relate_list = $db_query->resultArray();unset($db_query);

                $str .= '<div class="control-group">
                    <div class="controls">
                        <ul id="relate_result"></ul>
                    </div>
                    <div class="controls" id="news_relate_after_search">';
                $str .= '<div class="relate_element">';
                foreach($relate_list as $relate){
                    $str .= '<label class="checkbox">';
                    $str .= '<input type="checkbox" name="new_relate_list[]" checked="checked" value="'.$relate['new_id'].'" id="new_relate_list_'.$relate['new_id'].'">';
                    $str .= $relate['new_title'];
                    $str .= '<span style="margin-left:5px;padding:5px;color:red;font-weight:bold;font-size:14px;cursor:pointer;" onclick="NewsJS.del_relate(this);return false;">&times;</span>';
                    $str .= '</label>';
                }
                $str .= '</div></div></div>';
                return $str;
                break;

            case 'product' :
                if(!$relate_str) return self::CreateRelateProSection();
                $db_query = new db_query('SELECT pro_id,pro_name
                                    FROM products
                                    WHERE pro_active = 1 AND pro_id IN('.$relate_str.')');
                $relate_list = $db_query->resultArray();unset($db_query);

                $str .= '<div class="control-group">
                    <div class="controls">
                        <ul id="relate_pro_result"></ul>
                    </div>
                    <div class="controls" id="pro_relate_after_search">';
                $str .= '<div class="relate_element">';
                foreach($relate_list as $relate){
                    $str .= '<label class="checkbox">';
                    $str .= '<input type="checkbox" name="pro_relate_list[]" checked="checked" value="'.$relate['pro_id'].'" id="pro_relate_list_'.$relate['pro_id'].'">';
                    $str .= $relate['pro_name'];
                    $str .= '<span style="margin-left:5px;padding:5px;color:red;font-weight:bold;font-size:14px;cursor:pointer;" onclick="ProductJS.del_relate(this);return false;">&times;</span>';
                    $str .= '</label>';
                }
                $str .= '</div></div></div>';
                return $str;
                break;
        }
    }

    /*
     * Ham tao checksum cho giao dien
     */
    public static function CreateChecksumTemplate($tpl_name){
        return md5(md5('kelvin_bidiots') . sha1($tpl_name));
    }
    /*
     * Hàm in ra slide ảnh của 1 product
     */
    public static function GetSlideImage($pro_slide = ''){
        if(!$pro_slide){
            return '<div class="thumb add-img" id="add-item">
                        <span>Thêm ảnh</span>
                        <i class="uploading-msg"></i>
                    </div>
                    <input type="file" class="hidden" name="browser-file" id="browser-file">';
        }else{
            $html = '';
            $pro_slide = explode('|',$pro_slide);
            foreach($pro_slide as $img){
                $html .= '<div class="thumb">
                            <img src="../../../pictures/products/'.$img.'">
                            <input type="hidden" name="pro_slide[]" value="'.$img.'">
                            <div class="thumb-del">
                                <span class="label label-warning" onclick="ProductJS.slideDeleteItem(this)">Xóa</span>
                            </div>
                          </div>';
            }
            $html .= '<div class="thumb add-img" id="add-item">
                        <span>Thêm ảnh</span>
                        <i class="uploading-msg"></i>
                    </div>
                    <input type="file" class="hidden" name="browser-file" id="browser-file">';
            return $html;
        }
    }
    /*
     * Tạo folder template
     * folder để chmod 777
     */
    public static function CreateTemplateFolder($tpl_name){
        if(!$tpl_name) return false;
        $path = $_SERVER['DOCUMENT_ROOT'] . FOLDER_TEMPLATE . '/' . $tpl_name;
        //Nếu đã tồn tại folder rồi thì return;
        if(file_exists($path)){
            return true;
        }else{
            //Tạo folder template và các folder con
            @mkdir($path,0777);
            @mkdir($path . '/layout',0777);
            @mkdir($path . '/themes',0777);
            @mkdir($path . '/themes/css',0777);
            @mkdir($path . '/themes/img',0777);
            @mkdir($path . '/themes/js',0777);
            return true;
        }
    }
    /*
     * Get dropdown data
     */
    public static function GetDropdownData($table,$key_field,$value_field, $where_clause = '', $order_by = ''){
        $sql = 'SELECT '.$key_field.','. $value_field . '
                FROM '.$table.'
                WHERE 1 '.$where_clause.'
                ORDER BY '.($order_by ? $order_by : $key_field);
        $db_query = new db_query($sql);
        $arr_return = array();
        while($row = mysql_fetch_assoc($db_query->result)){
            $arr_return[$row[$key_field]] = $row[$value_field];
        }
        return $arr_return;
    }

    /*
     * Template admin
     */
    public static function TemplateAdd(){
        global $bg_table, $bg_errorMsg, $bg_filepath, $bg_extension, $limit_size,
                $filename, $isAdmin;
        if(!$isAdmin){
            return false;
        }
        //Tạo folder chứa template mới
        $tpl_name = getValue('tpl_name','str','POST','');
        self::CreateTemplateFolder($tpl_name);
        $path = $bg_filepath . $tpl_name .'/';
        $myform = new generate_form();
        $myform->add('tpl_name','tpl_name', 0, 0, '', 1, 'Bạn chưa nhập tên giao diện');
        $myform->add('tpl_active','tpl_active', 1, 0, 0);
        $myform->add('tpl_css_file','tpl_css_file', 0, 0 , '');
        $myform->add('tpl_js_file','tpl_js_file', 0, 0 , '');
        $myform->addTable($bg_table);
        $action = getValue('action','str','POST','');
        if($action == 'execute'){
            //Là admin cho up trực tiếp lên server file zip
            $upload = new upload('zip_file',$path,'zip','2048');
            $bg_errorMsg .= $upload->show_warning_error();
            $filename = $upload->file_name;
            //Giải nén file giao diện
            if($filename){
                $zip = new ZipArchive;
                $res = $zip->open($path . $filename);
                if ($res === TRUE) {
                    // extract it to the path we determined above
                    $zip->extractTo($path);
                    //xoa file zip
                    //kiem tra checksum
                    $checsum_file = self::CreateChecksumTemplate($tpl_name);
                    if(!file_exists($path . $checsum_file) || !$isAdmin){
                        //Checksum khong hop le - xoa toan bo thu muc vua upload
                        $bg_errorMsg .= '&bull; File checksum không hợp lệ<br>';
                        deleteDir($path);
                    }
                    //xóa file zip được up len
                    @unlink($path . $filename);
                    $zip->close();
                } else {
                    $bg_errorMsg .= '&bull; Không thể upload file zip<br>';
                }
            }

            if(!$bg_errorMsg){
                $db_insert = new db_execute($myform->generate_insert_SQL());
                unset($db_insert);
                redirect('listing.php');
            }
        }

    }
    public static function TemplateEdit($record_id){
        global $bg_table, $bg_errorMsg, $bg_filepath, $bg_extension, $limit_size,
               $id_field, $name_field, $tpl_css_file, $tpl_js_file, $isAdmin;
        $tpl_info = new db_query('SELECT * FROM '.$bg_table.' WHERE '.$id_field. '=' . $record_id);
        $tpl_info = mysql_fetch_assoc($tpl_info->result);
        if(!$tpl_info){
            exit();
        }
        $myform = new generate_form();
        $myform->add('tpl_active','tpl_active', 1, 0, 0);
        $action = getValue('action','str','POST','');
        if($action == 'execute'){
            //Nếu là admin thì cho thay đổi list file css và js
            if($isAdmin){
                $path = $bg_filepath . $tpl_info['tpl_name'] .'/';
                //Cho up lại giao diện code
                $upload = new upload('zip_file',$path,'zip','2048');
                $bg_errorMsg .= $upload->show_warning_error();
                $filename = $upload->file_name;
                //Giải nén file giao diện
                if($filename){
                    $zip = new ZipArchive;
                    $res = $zip->open($path . $filename);
                    if ($res === TRUE) {
                        // extract it to the path we determined above
                        $zip->extractTo($path);
                        //xoa file zip
                        //kiem tra checksum
                        $checsum_file = self::CreateChecksumTemplate($tpl_info['tpl_name']);
                        if(!file_exists($path . $checsum_file) || !$isAdmin){
                            //Checksum khong hop le - xoa toan bo thu muc vua upload
                            $bg_errorMsg .= '&bull; File checksum không hợp lệ<br>';
                            deleteDir($path);
                        }
                        //xóa file zip được up len
                        @unlink($path . $filename);
                        $zip->close();
                    } else {
                        $bg_errorMsg .= '&bull; Không thể upload file zip<br>';
                    }
                }

                //upload custom css và js file
                $path = $bg_filepath . $tpl_info[$name_field] . '/themes/';
                $upload_css = new upload('custom_css',$path . 'css/', 'css',$limit_size);
                $bg_errorMsg .= $upload_css->show_warning_error();
                $css_upload = $upload_css->file_name;
                if($css_upload) @rename($path . 'css/' . $css_upload, $path . 'css/custom.css');
                $upload_js = new upload('custom_js',$path . 'js/', 'js',$limit_size);
                $bg_errorMsg .= $upload_js->show_warning_error();
                $js_upload = $upload_js->file_name;
                if($js_upload) @rename($path . 'js/' . $js_upload, $path . 'css/custom.js');

                if(!$css_upload && !$js_upload){
                    $myform->add('tpl_css_file','tpl_css_file', 0, 0 , '');
                    $myform->add('tpl_js_file','tpl_js_file', 0, 0 , '');
                }
            }
            if($css_upload || $js_upload){
                $tpl_css_file = $tpl_info['tpl_css_file'] . '|' . 'custom.css';
                $tpl_js_file = $tpl_info['tpl_js_file'] . '|' . 'custom.js';
                $myform->add('tpl_css_file','tpl_css_file',0, 1, '');
                $myform->add('tpl_js_file','tpl_js_file',0, 1, '');
            }
            $myform->addTable($bg_table);
            $bg_errorMsg .= $myform->checkdata();
            if(!$bg_errorMsg){
                $db_update = new db_execute($myform->generate_update_SQL($id_field,$record_id));
                unset($db_update);
                redirect('listing.php');
            }
        }
    }

    /*
     * Product admin
     */
    public static function ProductAdd(){
        global $bg_table, $bg_errorMsg, $thumb_field, $bg_filepath, $bg_extension, $limit_size,
               $pro_date,$pro_slide, $pro_relate,$pro_news_relate,$pro_combo,$pro_promotion_list,
               $global_product_spec, $filename;
        $pro_date = time();
        //slide ảnh
        $pro_slide  = getValue('pro_slide','arr','POST','',3);

        //sản phẩm liên quan
        $pro_relate = getValue('pro_relate_list','arr','POST','');
        if(!empty($pro_relate)){
            $pro_relate = implode(',',$pro_relate);
        }else{
            $pro_relate = '';
        }
        //tin tức liên quan
        $pro_news_relate = getValue('new_relate_list','str','POST');
        if(!empty($pro_news_relate)){
            $pro_news_relate = implode(',',$pro_news_relate);
        }else{
            $pro_news_relate = '';
        }
        //phụ kiện đi kèm
        $pro_combo = getValue('comboDevide','arr','POST','');
        if($pro_combo){
            $pro_combo = implode(',',$pro_combo);
        }
        $pro_promotion_list = getValue('pro_promotion_list','arr','POST','');
        if($pro_promotion_list){
            $pro_promotion_list = implode(',',$pro_promotion_list);
        }


        $myform = new generate_form();
        $myform->add('pro_name','pro_name',0,0,'',1,'Bạn chưa nhập tên sản phẩm');
        $myform->add('pro_code_number','pro_code_number',0,0,'',0,'Bạn chưa nhập mã sản phẩm');
        $myform->add('pro_model_number','pro_model_number',0,0,'',0,'Bạn chưa nhập mã model');
        $myform->add('pro_cat_id','pro_cat_id',1,0,0,1,'Bạn chưa chọn danh mục');
        $myform->add('pro_factory','pro_factory',1,0,0,1,'Bạn chưa chọn hãng');
        $myform->add('pro_date','pro_date',1,1,0);
        $myform->add('pro_price','pro_price',1,0,0,1,'Bạn chưa nhập giá sản phẩm');
        $myform->add('pro_number_in_stock','pro_number_in_stock',1,0,0);
        $myform->add('pro_status_in_stock','pro_status_in_stock',1,0,0);
        $myform->add('pro_basic_info','pro_basic_info',0,0,'',1,'Bạn chưa nhập thông tin cơ bản của sản phẩm');
        $myform->add('pro_package','pro_package',0,0,'');
        $myform->add('pro_promotion','pro_promotion',0,0,'');
        $myform->add('pro_promotion_list','pro_promotion_list',0,0,'');
        $myform->add('pro_warranty','pro_warranty',0,0,'',0,'Bạn chưa nhập thông tin bảo hành');
        $myform->add('pro_color','pro_color',0,0,'');
        $myform->add('pro_video','pro_video',0,0,'');
        $myform->add('pro_relate','pro_relate',0,0,'');
        $myform->add('pro_news_relate','pro_news_relate',0,0,'');
        $myform->add('pro_type','pro_type',1,0,0);
        $myform->add('pro_detail','pro_detail',0,0,'');
        $myform->add('pro_combo','pro_combo',0,1,'');
        $myform->add('pro_active','pro_active',1,0,0);
        if($pro_slide){
            //chuyển ảnh từ thư mục temp sang
            foreach($pro_slide as $img){
                @rename('../../../temp/'.$img, $bg_filepath.$img);
            }
            $pro_slide = implode('|',$pro_slide);
            $myform->add('pro_slide','pro_slide',0,1,'');
        }
        /**
         * insert các giá trị vào bảng suggestion
         */
        $array_suggest_text = array();
        if(isset($_POST['pro_name']))   $array_suggest_text[] = $_POST['pro_name'];
        if(isset($_POST['pro_color']))  $array_suggest_text[] = $_POST['pro_color'];
        if(isset($_POST['pro_warranty']))  $array_suggest_text[] = $_POST['pro_warranty'];

        //Phần thông số kỹ thuật
        foreach($global_product_spec as $group){
            foreach($group['info'] as $spec){
                //push vào mảng array_suggest_text
                if(isset($_POST[$spec['spec']])){
                    $array_suggest_text[] = $_POST[$spec['spec']];
                }
                $myform->add($spec['spec'],$spec['spec'],0,0,'');
            }
        }
        //insert vào suggest_text
        insert_suggest_text($array_suggest_text);

        $myform->addTable($bg_table);
        $myform->removeHTML(0);
        $action = getValue('action','str','POST','');
        if($action == 'execute'){
            $bg_errorMsg .= $myform->checkdata();
            $upload = new upload($thumb_field,$bg_filepath,$bg_extension,$limit_size);
            $filename = $upload->file_name;
            if($filename){
                $myform->add($thumb_field,'filename',0,1,'');
            }
            $bg_errorMsg .= $upload->show_warning_error();
            if($bg_errorMsg == ''){
                $db_insert = new db_execute_return();
                $last_id = $db_insert->db_execute($myform->generate_insert_SQL());
                //Add seo meta
                addSeoMeta($last_id,$bg_table);
                if($db_insert->total > 0) redirect('listing.php');
            }
        }
    }
    public static function ProductEdit($record_id){
        global $bg_table, $bg_errorMsg, $thumb_field, $bg_filepath, $bg_extension, $limit_size,
               $pro_date,$pro_slide,$pro_relate, $pro_news_relate,$pro_combo,
               $global_product_spec, $filename,$id_field;
        $pro_date = time();
        //slide ảnh
        $pro_slide = getValue('pro_slide','arr','POST','',3);

        //sản phẩm liên quan
        $pro_relate = getValue('pro_relate_list','arr','POST','');
        if($pro_relate){
            $pro_relate = implode(',',$pro_relate);
        }else{
            $pro_relate = '';
        }
        //tin tức liên quan
        $pro_news_relate = getValue('new_relate_list','arr','POST','');
        if($pro_news_relate){
            $pro_news_relate = implode(',',$pro_news_relate);
        }else{
            $pro_news_relate = '';
        }
        //phụ kiện đi kèm
        $pro_combo = getValue('comboDevide','arr','POST','');
        if($pro_combo){
            $pro_combo = implode(',',$pro_combo);
        }

        /**
         * insert các giá trị vào bảng suggestion
         */
        $array_suggest_text = array();
        if(isset($_POST['pro_name']))   $array_suggest_text[] = $_POST['pro_name'];
        if(isset($_POST['pro_color']))  $array_suggest_text[] = $_POST['pro_color'];
        if(isset($_POST['pro_warranty']))  $array_suggest_text[] = $_POST['pro_warranty'];

        $myform = new generate_form();
        $myform->add('pro_name','pro_name',0,0,'',1,'Bạn chưa nhập tên sản phẩm');
        $myform->add('pro_code_number','pro_code_number',0,0,'',0,'Bạn chưa nhập mã sản phẩm');
        $myform->add('pro_model_number','pro_model_number',0,0,'',0,'Bạn chưa nhập mã model');
        $myform->add('pro_cat_id','pro_cat_id',1,0,0,1,'Bạn chưa chọn danh mục');
        $myform->add('pro_factory','pro_factory',1,0,0,1,'Bạn chưa chọn hãng sản xuất');
        $myform->add('pro_date','pro_date',1,1,0);
        $myform->add('pro_price','pro_price',1,0,0,1,'Bạn chưa nhập giá sản phẩm');
        $myform->add('pro_number_in_stock','pro_number_in_stock',1,0,0);
        $myform->add('pro_status_in_stock','pro_status_in_stock',1,0,0);
        $myform->add('pro_basic_info','pro_basic_info',0,0,'',1,'Bạn chưa nhập thông tin cơ bản của sản phẩm');
        $myform->add('pro_package','pro_package',0,0,'');
        $myform->add('pro_promotion','pro_promotion',0,0,'');
        $myform->add('pro_warranty','pro_warranty',0,0,'',0,'Bạn chưa nhập thông tin bảo hành');
        $myform->add('pro_color','pro_color',0,0,'');
        $myform->add('pro_video','pro_video',0,0,'');
        $myform->add('pro_relate','pro_relate',0,1,'');
        $myform->add('pro_news_relate','pro_news_relate',0,1,'');
        $myform->add('pro_type','pro_type',1,0,0);
        $myform->add('pro_detail','pro_detail',0,0,'');
        $myform->add('pro_combo','pro_combo',0,1,'');
        $myform->add('pro_active','pro_active',1,0,0);
        if($pro_slide){
            //chuyển ảnh từ thư mục temp sang
            foreach($pro_slide as $img){
                @rename('../../../temp/'.$img, $bg_filepath.$img);
            }
            $pro_slide = implode('|',$pro_slide);
            $myform->add('pro_slide','pro_slide',0,1,'');
        }
        //Phần thông số kỹ thuật
        foreach($global_product_spec as $group){
            foreach($group['info'] as $spec){
                //push vào mảng array_suggest_text
                if(isset($_POST[$spec['spec']])){
                    $array_suggest_text[] = $_POST[$spec['spec']];
                }
                $myform->add($spec['spec'],$spec['spec'],0,0,'');
            }
        }

        //insert vào suggest_text
        insert_suggest_text($array_suggest_text);


        $myform->addTable($bg_table);
        $myform->removeHTML(0);
        $action = getValue('action','str','POST','');
        if($action == 'execute'){
            $bg_errorMsg .= $myform->checkdata();
            $upload = new upload($thumb_field,$bg_filepath,$bg_extension,$limit_size);
            $filename = $upload->file_name;
            if($filename){
                $myform->add($thumb_field,'filename',0,1,'');
            }
            $bg_errorMsg .= $upload->show_warning_error();
            if($bg_errorMsg == ''){
                $db_insert = new db_execute($myform->generate_update_SQL($id_field,$record_id));
                editSeoMeta($record_id,$bg_table);
                if($db_insert->total > 0) redirect('listing.php');
            }
        }
    }
    /*
     * Factory admin
     */
    public static function FactoryAdd(){
        global $bg_table, $bg_errorMsg, $thumb_field, $bg_filepath, $bg_extension, $limit_size,
                $filename;
        $myform = new generate_form();
        $myform->add('fac_name','fac_name',0,0,'',1,'Bạn chưa nhập tên nhà sản xuất');
        $myform->addTable($bg_table);
        $action = getValue('action','str','POST','');
        if($action == 'execute'){
            $bg_errorMsg .= $myform->checkdata();
            $upload = new upload('fac_log',$bg_filepath,$bg_extension,$limit_size);
            $filename = $upload->file_name;
            if($filename){
                $myform->add($thumb_field,'filename',0,1,'');
            }
            $bg_errorMsg .= $upload->show_warning_error();
            if($bg_errorMsg == ''){
                $db_insert = new db_execute($myform->generate_insert_SQL());
                unset($db_insert);
                redirect('listing.php');
            }
        }
    }
    public static function FactoryEdit($record_id){
        global $bg_table, $bg_errorMsg, $thumb_field, $bg_filepath, $bg_extension, $limit_size, $id_field,
                $filename;
        $myform = new generate_form();
        $myform->add('fac_name','fac_name',0,0,'',1,'Bạn chưa nhập tên nhà sản xuất');
        $myform->add('fac_cat_type','fac_cat_type',0,0,'');
        $myform->addTable($bg_table);
        $action = getValue('action','str','POST','');
        if($action == 'execute'){
            $bg_errorMsg .= $myform->checkdata();
            $upload = new upload($thumb_field,$bg_filepath,$bg_extension,$limit_size);
            $filename = $upload->file_name;
            if($filename){
                $myform->add($thumb_field,'filename',0,1,'');
                delete_file($bg_table,$id_field,$record_id,$thumb_field,$bg_filepath);
            }
            $bg_errorMsg .= $upload->show_warning_error();
            if($bg_errorMsg == ''){
                $db_insert = new db_execute($myform->generate_update_SQL($id_field,$record_id));
                unset($db_insert);
                redirect('listing.php');
            }
        }
    }
}
?>